package com.gzy.wb.server;

import com.gzy.wb.controller.para.MyLogPara;
import com.gzy.wb.core.Page;
import com.gzy.wb.core.R;
import com.gzy.wb.exception.AppException;
import com.gzy.wb.model.MyLog;
import com.gzy.wb.repository.MyLogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.AreaAveragingScaleFilter;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class MyLogServer {
    @Autowired
    MyLogRepository repository;


    public List<MyLog> findAll(Integer id) {
        return repository.findAllByUserid(id);
    }

    public MyLog findMyLogByIdAndUserid(Long id, Integer userid) {
        Optional<MyLog> byId = repository.findById(id);
        if (byId.isEmpty()){
            throw new AppException("数据未找到",R.Code.NotFound);
        }
        if (!Objects.equals(byId.get().getUserid(),userid)){
            throw new AppException("数据未找到",R.Code.NotFound);
        }
        return byId.get();
    }

    public MyLog create(Integer userid, MyLogPara log) {
        MyLog myLog = new MyLog();
        myLog.setContent(log.getContent());
        myLog.setUserid(userid);
        myLog.setCreateAt(System.currentTimeMillis());
        return repository.save(myLog);
    }

    public void delete(Integer userid, Long id) {
        Optional<MyLog> byId = repository.findById(id);
        if (byId.isEmpty()){
            throw new AppException("数据未找到1",R.Code.NotFound);
        }
        if (!Objects.equals(byId.get().getUserid(),userid)){
            throw new AppException("数据未找到2",R.Code.NotFound);
        }
        repository.deleteById(id);
    }

    public MyLog update(Integer userid, Long id, MyLogPara logPara) {
        Optional<MyLog> byId = repository.findById(id);
        if (byId.isEmpty()){
            throw new AppException("数据未找到3",R.Code.NotFound);
        }
        if (!Objects.equals(byId.get().getUserid(),userid)){
            throw new AppException("数据未找到4",R.Code.NotFound);
        }
        MyLog myLog = byId.get();
        myLog.setContent(logPara.getContent());
        MyLog save = repository.save(myLog);
        return save;
    }

    public Page<MyLog> findUserByPage(Integer id, Long page, Long size) {
        Page<MyLog> result = new Page<>();

        long offset = size * (page-1);
        List<MyLog> myLogs = repository.pageWhere(id, offset, size);

        long count = repository.countByUser(id);



        // 21
        // size 10
        // 21/10=2
        // +1      21%10=1
        // 不等于0 就加1

        long p1 = count / size;
        long mod = count % size;
        if (mod != 0){
            p1+=1;
        }

        result.setTotalPage(p1);
        result.setData(myLogs);
        result.setCurPage(page);
        result.setSize(size);
        result.setTotalSize(count);

        return result;
    }
}
